import os
from flask import Blueprint, send_from_directory, jsonify
from flask import current_app
from models.event import EventModel
from utils import restful
from hooks import login_auth


bp = Blueprint('swiper', __name__, url_prefix='/swiper')


# 1、获取swiper图片信息，先找活动的图片信息，找不到再传默认图
@bp.route('/getAll')
def get_swipers():
    swipers = []
    count = EventModel.query.count()
    if count >= 3:
        events = EventModel.query.order_by(EventModel.finish_time.desc()).limit(3)
        for event in events:
            tmp = {'id': event.event_id, 'url': event.cover_img}
            swipers.append(tmp)
    else:
        swipers = get_default_swipers()
    return restful.ok(data={'swipers': swipers})


# 2、获取swiper图片资源(默认swiper)
@bp.route('/get/<string:file_name>')
def get_swiper(file_name):
    try:
        image_dir = os.path.join(current_app.config['IMAGE_ROOT'], 'swiper')
        # 返回图片
        return send_from_directory(image_dir, file_name)
    except Exception as e:
        current_app.logger.error(e)
        return str(e)


def get_default_swipers():
    image_dir = os.path.join(current_app.config['IMAGE_ROOT'], 'swiper')
    base_server = current_app.config['BASE_SERVER']
    dir_list = os.listdir(image_dir)
    print(dir_list)
    swipers = []
    for filename in dir_list:
        url = base_server+'/swiper/get/'+filename
        swipers.append({'id': '', 'url':url})
    return swipers
